# !python3
# -*- coding: utf-8 -*-

import json
import os
import platform
import queue
import threading
import time
import tkinter as tk
import tkinter.font as tkFont
import tkinter.messagebox as tkmsgbox
import tkinter.scrolledtext as tkSclText
from os import path
from random import randint

from chatterbot import ChatBot
import itchat
import jieba
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from echarts import Echart, Legend, Pie
from itchat.content import *
from PIL import Image, ImageTk
import requests
from wordcloud import STOPWORDS, ImageColorGenerator, WordCloud

here = path.dirname(__file__) if "__file__" in locals() else '.'

icon = None
icon_fileName = path.join(here, 'img', 'wechat.png')

logined_flag = False
refresh_flag = False


lock = threading.Lock()

msg_to_process = queue.Queue()
auto_rep = queue.Queue()

history_msg = {}
chatbot_response_friends = []

chatbot = ChatBot(
        'Litter Zero',
        storage_adapter='chatterbot.storage.SQLStorageAdapter',
        database=path.join(here, 'res', 'chatbot_database.sqlite3')
)
# chatbot 的推出指令集
quit_cmds = []
user_chatbot_quit_list = path.join(here, 'chatbot_quit.txt')
if path.exists(user_chatbot_quit_list):
    with open(user_chatbot_quit_list, 'r') as f:
        for line in f:
            quit_cmds.append(line)

else:
    quit_cmds = ['[Q]']

# 定义itchat接收到消息的操作
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_response(msg):
    lock.acquire()
    global refresh_flag, msg_to_process, chatbot_response_friends
    try:
        # 放入消息队列
        refresh_flag = True
        msg_to_process.put(msg)
        # 自动回复
        if msg.user in chatbot_response_friends:
            auto_rep.put(msg)
    finally:
        lock.release()


@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO, FRIENDS, VOICE])
def others_response(msg):
    # 该客户端不处理这些消息，仅提示用户在手机上查看
    lock.acquire()
    global refresh_flag, msg_to_process
    try:
        # 把提示放入消息队列
        refresh_flag = True
        tip_msg_like = imitateItchatMsg(
            toUserName=msg.get('ToUserName'),
            fromUserName=msg.get('FromUserName'),
            text = '接收到一条消息，请在手机微信中查看。',
            user=msg.user
        )
        msg_to_process.put(tip_msg_like)
    finally:
        lock.release()


@itchat.msg_register(
    [TEXT, PICTURE, RECORDING, ATTACHMENT, VIDEO],
    isGroupChat=True
)
def group_text_reply(msg):
    # 该客户端不处理这些消息
    lock.acquire()
    global refresh_flag, msg_to_process
    try:
        # 把提示放入消息队列
        refresh_flag = True
        msg_to_process.put(msg)
    finally:
        lock.release()


class SignIn(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master

        self.master.title('mineWeChat —— 登录')
        self.master.geometry('987x610+233+144')
        self.master.resizable(width=False, height=False)
        self.welcome_text = tk.StringVar()
        self.create_widgets()

        self.pack()

    def create_widgets(self):
        # welcome frame
        self.frm = tk.Frame(bd=0, height=610, width=89)
        self.frm.pack(side=tk.TOP)

        # icon of mineWeChat
        global icon
        img_open = Image.open(icon_fileName)
        icon = ImageTk.PhotoImage(img_open)
        imgLabel = tk.Label(self.frm, image=icon)
        imgLabel.pack()

        # welcome text
        self.welcomeLabel = tk.Label(
            self.frm,
            textvariable=self.welcome_text
        )
        self.welcome_text.set(
            '\n\n欢迎使用mineWeChat微信客户端。\nWelcome to mineWeChat.\n\n'
        )
        self.welcomeLabel.pack()

        # buttons of login
        self.buttons = tk.Frame(self.frm, bd=21, height=34, width=55)
        self.buttons.pack()

        self.loginButton = tk.Button(
            self.buttons,
            text='登录',
            width=12,
            command=self.command_login
        )
        self.loginButton.pack(side=tk.LEFT)

        self.autologinButton = tk.Button(
            self.buttons,
            text='自动登录',
            width=12,
            command=self.command_auto_login
        )
        self.autologinButton.pack(side=tk.RIGHT)

        # addition
        self.addition_text = '\n\n\nDesigned by CDFMLR with peace & love.\nPowered by itchat.'
        self.addition = tk.Label(
            self.frm,
            text=self.addition_text,
            font=tkFont.Font(family='Symbol', size=8)
        )
        self.addition.pack(side=tk.BOTTOM)

    def command_login(self):
        self.welcomeLabel['text'] = '\n\n请使用微信手机端扫描弹出的二维码，并确认登录。\n\n\n'
        self.welcomeLabel.update()
        itchat.login(loginCallback=self.finish)

    def command_auto_login(self):
        self.welcome_text.set('\n\n请使用微信手机端确认登录。\n\n\n')
        self.welcomeLabel.update()
        itchat.auto_login(hotReload=True, loginCallback=self.finish)

    def finish(self):
        global logined_flag
        logined_flag = True
        self.welcome_text.set(
            '\n\n登录成功!\n欢迎您, %s.\n\n' % getReadableName(itchat.get_friends(update=True)[0])
        )
        self.welcomeLabel.update()
        time.sleep(0.5)
        self.master.destroy()


class ChatRoom(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title('mineWeChat')
        self.master.geometry('987x610+233+144')
        self.master.resizable(width=False, height=False)
        self.create_widgets()
        self.pack()
        itchat.run(blockThread=False)
        self.refresh()


    def create_widgets(self):
        global logined_flag

        self.index_of_now = 0
        self.friend_of_now = itchat.get_friends()[0]

        if not logined_flag:
            self.master.destroy()
        else:
            # basic frame
            self.frm = tk.Frame(bd=0, height=610, width=987)
            # self.frm.pack(side=tk.TOP)
            self.frm.place(bordermode=tk.OUTSIDE, height=610, width=987, x=0, y=0)

            # friends: ~~head~~, list, foot(See statistics of friends)
            self.frds = tk.Frame(self.frm, bd=0, height=610, width=233)
            self.frds.place(bordermode=tk.OUTSIDE, height=610, width=233, x=0, y=0)

            '''
            frds_head = tk.Frame(frds, bd=0, height=10, width=377)
            frds_head.pack(side=tk.TOP)
            '''

            # List
            self.frds_list = tk.Frame(self.frds, bd=10, height=600, width=233)
            self.frds_list.place(bordermode=tk.OUTSIDE, height= 600, width=233, x=0, y=0)

            self.frds_list_scrollbar = tk.Scrollbar(self.frds_list)
            self.frds_list_scrollbar.pack(side=tk.RIGHT, fill=tk.BOTH)

            self.frds_list_friends = tk.Listbox(
                self.frds_list,
                yscrollcommand=self.frds_list_scrollbar.set
            )

            # Full the list
            # in v0.0.0, there are friends only, groups are baned
            allMyFriends = itchat.get_friends()

            for friend in allMyFriends:
                name = getReadableName(friend)
                self.frds_list_friends.insert(tk.END, name)

            if self.frds_list_friends.size() != 0:
                self.frds_list_friends.activate(0)
            
            self.frds_list_friends.place(bordermode=tk.OUTSIDE, height= 500, width=200, x=8, y=13)



            self.frds_list_friends.bind('<ButtonRelease-1>', self.change_chatRoom)

            # Foot
            self.frds_foot = tk.Frame(self.frds, bd=2, height=100, width=233)
            self.frds_foot.place(bordermode=tk.OUTSIDE, height= 80, width=233,x=0, y=520)

            self.frd_foot_buttons = tk.Frame(self.frds_foot, bd=0, height=100, width=233)
            self.frd_foot_buttons.pack(side=tk.BOTTOM)

            self.friends_signCloud = tk.Button(
                self.frd_foot_buttons,
                text='好友词云',
                command=lambda: friendsCloud(allMyFriends)
            )
            self.friends_sexChart = tk.Button(
                self.frd_foot_buttons,
                text='好友性别比例',
                command=lambda: friendsSex(allMyFriends)
                )
            
            self.friends_signCloud.pack(side=tk.LEFT)
            self.friends_sexChart.pack(side=tk.LEFT)

            # chat: head, list, foot(edit & send)
            self.chat = tk.Frame(self.frm, bd=0, height=610, width=610)
            self.chat.place(x=270, y=0, height=610, width=610)
            # head

            self.place_head()

            self.chat_list = tk.Frame(self.chat)
            self.chat_list.place(x=8, y=58, height=400, width=600)
            # list, 纯文本样式
            self.chat_list_text = tkSclText.ScrolledText(self.chat_list, bd=5, bg='#eee')
            self.chat_list_text.pack(fill=tk.BOTH)

            self.chat_list_text.tag_config(
                'others_head',
                foreground='#2222ff',
                font='helvetica 14 bold',
                justify='left'
            )
            self.chat_list_text.tag_config(
                'others_content',
                justify='left'
            )
            self.chat_list_text.tag_config(
                'self_head',
                foreground='#22cc22',
                font='helvetica 14 bold',
                justify='right'
            )
            self.chat_list_text.tag_config(
                'self_content',
                justify='right'
            )


            '''
            # chat_list_text 改为 tk.Frame, 带头像的样式, 由于 Frame 的滚动条实现麻烦, 在这里没有采用
            def place_dialog(msg):
                msgFrm = tk.Frame(self.chat_list, width=600)
                # portrait (head img)
                name = msg.user.get('RemarkName') or msg.user.get('NickName') or msg.user.get('UserName')   # SHOULD USE `getReadableName`
        
                head_img_file_path = './img/head/%s' % name     # SHOULD USE `path.join` here!

                if not os.path.exists(head_img_file_path):      # if not exist: download it.
                    itchat.get_head_img(userName=msg.user['UserName'], picDir=head_img_file_path)

                if msg.user != itchat.get_friends()[0]:     # friend
                    director = tk.LEFT
                    bkg_color = '#d04844'
                else:       # user
                    director = tk.RIGHT
                    bkg_color = '#70c179'

                img_open = Image.open(head_img_file_path)
                head_img = ImageTk.PhotoImage(img_open, (50, 50))
                portrait = tk.Button(msgFrm, bd=0, height=50, width=50, bg='#FAEBD7', image=head_img)
                portrait.pack(side=director)
                # dialogue (message)
                dialogue = tk.Message(
                    msgFrm,
                    bg=bkg_color,
                    text=msg.text
                )
                dialogue.pack(side=director)

                msgFrm.pack(side=tk.TOP, fill=tk.X)
                self.chat_list.update()
            '''

            # foot
            self.chat_foot = tk.Frame(self.chat, bd=0, width=600, height=120)
            self.chat_foot.place(height=120, width=600, x=4, y=480)

            # scrolledText (Edit)
            self.editPad = tkSclText.ScrolledText(self.chat_foot, bg='#def')
            self.editPad.place(height=120, width=400, x=0, y=0)

            # Functions (send, flood, bot)
            # send
            sendButton = tk.Button(
                self.chat_foot,
                text='发送',
                command=self.send_command
            )
            sendButton.place(x=420, y=0)
            # flood
            floodFrm = tk.Frame(self.chat_foot, bg='#e9daee')
            floodFrm.place(x=420, y=40, height=30, width=200)
            
            self.floodTimes = tk.Spinbox(floodFrm, from_=0, to=10, width=2)
            self.floodTimes.pack(side=tk.LEFT)

            self.floodChockMode = tk.IntVar()
            floodChock = tk.Checkbutton(
                floodFrm,
                text='结巴',
                variable=self.floodChockMode,
                onvalue = 1,
                offvalue = 0
            )
            floodChock.pack(side=tk.LEFT)

            floodButton = tk.Button(
                floodFrm,
                text='刷屏',
                command=self.flood_command
            )
            floodButton.pack(side=tk.LEFT)
            # chatbot
            self.chatbot_on = tk.IntVar()
            self.chatbot_on.set(0)
            self.botButton = tk.Checkbutton(
                self.chat_foot,
                text='机器人自动回复',
                variable=self.chatbot_on,
                onvalue = 1,
                offvalue = 0,
                command=self.change_chatbot
            )
            self.botButton.place(x=420, y=80)


    def notice(self, content, color='#EBCE87'):
        self.chat_head_notice['bg'] = color
        self.chat_head_notice['text'] = content
        

    def delive_msg(self, msg, kind='Message'):
        if msg.user == self.friend_of_now:
            self.place_dialog(msg)
        else:
            from_name = getReadableName(msg.user)
            if kind == 'new_msg':
                self.notice('您收到了来自<%s>的新消息。' % from_name)
            elif kind == 'auto_rep':
                self.notice('机器人自动回复了<%s>。' % from_name)
            else:
                self.notice('有关于<%s>的新消息。' % from_name)
            self.chat_head_notice.update()
            msg_to_process.put(msg)


    def refresh(self):
        global refresh_flag, msg_to_process, chatbot_response_friends, auto_rep
        lock.acquire()
        # print('Refresh:', refresh_flag)
        if refresh_flag:
            try:
                # 处理接受到的新消息
                ## 把 msg_to_process Queue 中的所有 msg 取出到一个 list 中，遍历list 做deliver后，后把剩余放回Queue.
                items = []
                while not msg_to_process.empty():
                    items.append(msg_to_process.get())

                ### print(items)
                for item in items:
                    self.delive_msg(item, kind='new_msg')

                # 处理接收到的要自动回复的消息
                ## 把 auto_rep Queue 中的 msg 逐个交给 chatbot_command 处理
                while not auto_rep.empty():
                    self.chatbot_command(auto_rep.get())
            finally:
                refresh_flag = False

        lock.release()
        self.after(1000, self.refresh)

    def change_chatbot(self):
        # 刷新自动回复
        var_of_chatbot = self.chatbot_on.get()
        if var_of_chatbot == 1:
            if self.friend_of_now not in chatbot_response_friends:
                chatbot_response_friends.append(self.friend_of_now)
                self.notice('已开启对<%s>的自动回复。' % getReadableName(self.friend_of_now))
        else:   # var_of_chatbot == 0
            if self.friend_of_now in chatbot_response_friends:
                chatbot_response_friends.pop(
                    chatbot_response_friends.index(self.friend_of_now)
                )
                self.notice('已停止了对<%s>的自动回复。' % getReadableName(self.friend_of_now))


    def change_chatRoom(self, event):
        global refresh_flag
        if self.frds_list_friends.curselection() and self.frds_list_friends.curselection()[0] != self.index_of_now:
            oldOne = self.friend_of_now
            self.index_of_now = self.frds_list_friends.curselection()[0]
            self.friend_of_now = itchat.get_friends()[self.index_of_now]
            newOne = self.friend_of_now

            self.place_head()
            # Save the history of the old one
            oldText = self.chat_list_text.get(1.0, tk.END)
            history_msg[oldOne.get('UserName')] = oldText
            # Clear it
            self.chat_list_text.delete(1.0, tk.END)
            # Get history of the new one
            try:
                newText = history_msg[newOne.get('UserName')]
            except KeyError:
                newText = ''
            # Display it
            self.chat_list_text.insert(1.0, newText)
            if self.friend_of_now not in chatbot_response_friends:
                self.botButton.deselect()
            else:
                self.botButton.select()
            refresh_flag = True


    def place_dialog(self, msg):
        # line 1: Colored sender name and time
        # line 2: the content of massage's Text
        userself = itchat.get_friends()[0]
        from_name = getReadableName(msg.user)
        msg_time = msg.get('CreateTime') or time.time()          # 时间戳
        msg_time = time.asctime(time.localtime(msg_time))        # 转化为本地时间字符串

        echo_head = '%s\t%s\n' % (from_name, msg_time)
        echo_content = '%s\n\n' % msg.get('Text')

        if (msg.user == userself) or (msg.get('FromUserName') == userself.get('UserName')):
                self.chat_list_text.insert(tk.END, echo_head, 'self_head')
                self.chat_list_text.insert(tk.END, echo_content, 'self_content')
        else:
                self.chat_list_text.insert(tk.END, echo_head, 'others_head')
                self.chat_list_text.insert(tk.END, echo_content, 'others_content')


    def place_head(self):
        self.chat_head = tk.Frame(self.chat, bd=0, height=50, width=610, bg='#87CEEB')
        self.chat_head.place(x=8, y=8, height=50, width=600)

        selected = self.frds_list_friends.curselection()
        try:
            now_chatting_friend = itchat.get_friends()[selected[0]]
        except:
            now_chatting_friend = itchat.get_friends()[0]   # userself

        name = getReadableName(now_chatting_friend)
        # portrait (head img)
        head_img_file_path = path.join(here, 'img', 'head', '%s.jpg' % name)

        if not os.path.exists(head_img_file_path):      # if not exist: download it.
            itchat.get_head_img(
                userName=now_chatting_friend['UserName'],
                picDir=head_img_file_path
            )

        img_open = Image.open(head_img_file_path)
        head_img = ImageTk.PhotoImage(img_open, (50, 50))

        self.chat_head_img = tk.Button(
            self.chat_head,
            bd=0,
            height=50,
            width=50,
            bg='#FAEBD7',
            image=head_img
        )
        self.chat_head_img.place(x=550, y=0, height=50, width=50)

        # echo now chatRoom and Notice
        self.chat_head_name = tk.Label(
            self.chat_head,
            bd=0,
            bg='#87CEEB',
            text='与 <%s> 聊天中...' % name
        )
        self.chat_head_name.pack()

        self.chat_head_notice = tk.Label(
            self.chat_head,
            bd=1,
            bg='#87CEEB',
            text=''
        )
        self.chat_head_notice.pack(side=tk.BOTTOM)

    
    def send_command(self):
        try:
            now_chatting_friend = self.friend_of_now
            msg_to_send = self.editPad.get(1.0, tk.END)
        except Exception as e:
            now_chatting_friend = itchat.get_friends()[0]   # userself
            msg_to_send = '【mineWeChat】消息未发送！\n详情:\n>时间: %s\n>消息: %s\n>错误:\n%s' % (
                time.localtime(),
                self.editPad.get(1.0, tk.END),
                e
            )
        finally:
            # 重置editPad
            self.editPad.delete(1.0, tk.END)
            # 发送
            itchat.send(msg=msg_to_send, toUserName=now_chatting_friend.get('UserName'))
            # 显示该消息
            me = itchat.get_friends()[0]
            msg_like = imitateItchatMsg(
                fromUserName=me.get('UserName'),
                text=msg_to_send,
                user=me
            )
            self.place_dialog(msg_like)


    def flood_command(self):
        try:
            now_chatting_friend = self.friend_of_now
            msg_to_send = self.editPad.get(1.0, tk.END)
            times = int(self.floodTimes.get())
            chock = self.floodChockMode.get()
            sendFloodMsg(now_chatting_friend, msg_to_send, times, chock)
        except Exception as e:
            now_chatting_friend = itchat.get_friends()[0]   # userself
            msg_to_send = '【mineWeChat】消息未发送！\n详情:\n>时间: %s\n>消息: %s\n>错误:\n%s' % (
                time.localtime(),
                self.editPad.get(1.0, tk.END),
                e
            )
            itchat.send(
                msg=msg_to_send,
                toUserName=now_chatting_friend.get('UserName')
            )
        finally:
            # 重置editPad
            self.editPad.delete(1.0, tk.END)
            # 显示该消息
            me = itchat.get_friends()[0]
            tip = '<{0}>\nx{1}'.format(msg_to_send[:-1], times) + ' (结巴)' * chock
            msg_like = imitateItchatMsg(
                fromUserName=me.get('UserName'),
                text=tip,
                user=me
            )
            self.place_dialog(msg_like)


    def chatbot_command(self, msg):
        try:
            # 检测是否是关闭指令
            if msg.get('Text') in quit_cmds:
                chatbot_response_friends.pop(
                    chatbot_response_friends.index(msg.user)
                )
                self.change_chatbot()
                self.notice('通过指令关闭了对<%s>的自动回复。' % getReadableName(msg.user))
            else:
                raw_response = chatbotResponse(msg)
                res_text = '[机器人自动回复]\n%s' % raw_response
                # 发送
                itchat.send(
                    toUserName=msg.user.get('UserName'),
                    msg=res_text
                )
                # 显示
                userself = itchat.get_friends()[0]
                msg_like = imitateItchatMsg(
                    toUserName=msg.user.get('UserName'),
                    fromUserName=userself.get('UserName'),
                    text=res_text,
                    user=msg.user,
                )
                
                self.delive_msg(msg_like, kind='auto_rep')
                
        except Exception as e:
            itchat.send(
                toUserName=itchat.get_friends()[0].get('UserName'),
                msg = '机器人自动回复失败！\n错误详情:\n %s' % e
            )


def getReadableName(user):
    # 获取一个可读的名字
    res = user.get('RemarkName') or user.get('NickName') or user.get('UserName')
    return res


def imitateItchatMsg(*, toUserName='', fromUserName='', text='', user=None):
    # 用这个函数得到一个模仿itchat的msg的对象，该对象提供部分与msg相似的操作，用来解决自己发送的消息的place_dialog
    class imitateMsg(object):
        def __init__(self,toUserName, fromUserName, user, text):
            self.toUserName = toUserName
            self.fromUserName = fromUserName
            self.user = user
            self.text = text

        def get(self, n):
            if n == 'FromUserName':
                r = self.fromUserName
            elif n== 'ToUserName':
                r == self.toUserName
            elif n == 'User':
                r = self.user
            elif n == 'Text':
                r = self.text
            else:
                r = None
            return r

    return imitateMsg(toUserName, fromUserName, user, text)


def friendsSex(friends):
    male = female = others = 0
    for i in friends[1:]:
        sex = i["Sex"]
        if sex == 1:
                male += 1
        elif sex == 2:
                female += 1
        else:
                others += 1

    total = len(friends[1:])
    print('Male:', male, '\t', male/total)
    print('Female:', female, '\t', female/total)
    print('Others:', others, '\t', others/total)
    '''
    male = female = others = 1
    total = 3
    friends = [{'NickName': 'asd'}]
    '''
    chart = Echart('%s的微信好友性别比例' % (friends[0]['NickName']), 'from mineWeChat')
    chart.use(Pie('WeChat',
                [
                    {
                        'value': male,
                        'name': u'男性 %.2f%%' % (male / total * 100)
                        },
                    {
                        'value': female,
                        'name': u'女性 %.2f%%' % (female / total * 100)
                        },
                    {
                        'value': others,
                        'name': u'其他 %.2f%%' % (others / total * 100)
                        }
                ],
                radius=["50%", "70%"]))
    chart.use(Legend(["male", "female", "others"]))
    del chart.json["xAxis"]
    del chart.json["yAxis"]
    # chart.plot()
    chart.save(here, '%s-wechat_friends_sex_chart' % (friends[0]['NickName']))

    # to open a file in the user's preferred application (in GUI),
    # we are expect to use different command for different system:
    #   > Microsoft Windows(`filePath`),
    #   > Mac OS X(`open filePath`),
    #   > Linux(`xdg-open filePath` for gnome or kde)
    sysName = platform.system()
    cmd = ''
    file_path = path.join(here, '%s-wechat_friends_sex_chart.html' % (friends[0]['NickName']))
    if sysName == 'Windows':
        cmd = '%s' % file_path
    elif sysName == 'Darwin':
        cmd = 'open %s' % file_path
    elif sysName == 'Linux':
        # Linux 需要检测有没有使用可用的桌面环境
        ret = os.system('ps -A | egrep -i "gnome|kde" | wc -l')
        if ret:     # xdg-open 可用
            cmd = 'xdg-open %s' % file_path
    os.system(cmd)


def friendsCloud(friends):
    information = []
    for friend in friends:
        information.append(friend['RemarkName'])
        information.append(friend['Province'])
        information.append(friend['City'])
        information.append(friend['Signature'])

    print(information)
    meg = ''.join(information)
    words = jieba.cut(meg, cut_all=True)
    text = " ".join(words)

    # 绘制词云
    d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
    maskPic = np.array(Image.open(path.join(d, 'img', "a.png")))

    wc = WordCloud(
            font_path=path.join(d, 'font', 'shou.ttf'),
            background_color="black",
            mask=maskPic,
            contour_width=2, 
            contour_color='steelblue'
            )
    wc.generate(text)
    # image_colors = ImageColorGenerator(maskPic)

    # store to file
    wc.to_file(path.join(d, "save.png"))

    # show
    plt.imshow(wc)
    plt.axis("off")
    plt.show()


def sendFloodMsg(obj, cont, times, chock):
    if chock == 0:
        for _ in range(times):
            obj.send(cont)
            time.sleep(0.03 * randint(1, 5))
    else:
        fwd = ''
        for w in cont:
            for _ in range(randint(1, times)):
                fwd += w
            obj.send(fwd)
            time.sleep(0.03 * randint(1, 5))


def chatbotResponse(msg):
    # 使用本机 chatterbot 尝试获取回复
    responseText = chatbot.get_response(msg.text)
    print('(response from chatterbot:[%s])' % responseText)
    # 若 chatterbot 不能解决，再使用 tuling123 尝试获取回复
    if ('%s' % responseText) == '':
        KEYS = [
                '45fdd5e7afb74a4d9a7247c2d064d90d',
                '1fd7b36538434a64ac2c087d0c9ea6af'
                ]
        KEY = KEYS[-1]
        URL = 'http://openapi.tuling123.com/openapi/api/v2'
        data = {
                "reqType": 0,
                "perception": {
                    "inputText": {
                        "text": msg.text
                    },
                },
                "userInfo": {
                    "apiKey": KEY,
                    "userId": "123"
                }
        }
        r = requests.post(URL, data=json.dumps(data)).json()
        responseText = r.get('results')[0].get('values').get('text')
        print('(response from tuling123:[%s])' % responseText)

    return responseText


if __name__ == '__main__':
    signIn_master = tk.Tk()
    signIn_window = SignIn(master=signIn_master)
    signIn_window.mainloop()
    if logined_flag:
        chatRoom_master = tk.Tk()
        chatRoom_window = ChatRoom(master=chatRoom_master)
        chatRoom_window.mainloop()

    itchat.logout()
